/**
* @description: 待办工单 -》 通信光缆巡视 -》 已巡视光缆-纤芯核查列表 -》 单纤芯核查
**/

<template>
  <view class="power-inspect-main">
    <nav-bar class="header" back title="纤芯核查" @goBack="goBack"/>
    <view class="main-container">
      <!--纤芯信息-->
      <plateTitle :title="fiberTitle" class="plate-title-1"/>
      <view class="base-info-container">
        <van-cell-group>
          <van-cell v-for="(item,index) in fiberData.baseInfoData" :key="index" :title="item.title" :value="item.value"/>
        </van-cell-group>
      </view>
      
      <!--光路信息-->
      <plateTitle title="光路信息" class="plate-title-2"/>
      <view class="base-info-container">
        <van-cell-group>
          <van-cell v-for="(item,index) in circuitData.baseInfoData" :key="index" :title="item.title" :value="item.value"/>
        </van-cell-group>
      </view>
      
      <!--巡视信息-->
      <plateTitle title="巡视信息" class="plate-title-2"/>
      <view class="patrol-info-container">
        <van-field
          readonly
          clickable
          input-align="right"
          right-icon="arrow"
          :value="isCoincide"
          label="台账信息与现场信息是否一致"
          placeholder="点击选择"
          @click="checkPickerList('isCoincide')"
        />
        <view v-show="isCoincide === '一致'"
              style="color: #417ADC;
              font-size: 14px;
              padding: 10px 16px;"
              @click="checkPickerList('lineMatch')">
          选择配对纤芯
          <span style="float: right; color: #333">配对纤芯：{{saveParams.line_match_name}}</span>
        </view>
        <!--        <van-radio-group v-show="isCoincide === '不一致'"-->
        <!--                         v-model="operation"-->
        <!--                         icon-size="15px"-->
        <!--                         checked-color="#417ADC">-->
        <!--          <van-radio name="noExist">现场无此设备，将标记此设备状态为“不存在”</van-radio>-->
        <!--          <van-divider dashed />-->
        <!--          <van-radio name="modify">现场设备信息不一致，将标记此设备状态为“修改”</van-radio>-->
        <!--        </van-radio-group>-->
      </view>
      
      <!--按钮-->
      <van-button block @click="submit">{{ buttonText() }}</van-button>
      
      <!--选择器-->
      <van-popup v-model="showPicker" position="bottom">
        <van-picker
          show-toolbar
          :columns="currentPickerList"
          @confirm="pickerConfirm"
          @cancel="showPicker = false">
          <template #option="item" v-if="currentPickerItem === 'lineMatch'">
            <div class="picker-option">
              <div>{{ item.text }}</div>
              <!--纤芯未占用或无占用状态时，显示空，否则显示光路名称-->
              <div class="circuit">
                <span>{{item.origin.IS_OCCUPY === undefined || item.origin.IS_OCCUPY === "5" ? "" : item.origin.OCCUPY_STATE}}</span>
              </div>
              <!--              <div class="circuit">1000kV11至11光缆1000kV11至11光缆1000kV11至11光缆1000kV11至11光缆</div>-->
              <div style="width: 16px;">
                <van-icon name="success" v-show="saveParams.line_match_name === item.text" color="#417ADC"/>
              </div>
            
            </div>
          </template>
        </van-picker>
      </van-popup>
    </view>
  </view>
</template>

<script>
import navBar from "../../../../../components/common/nav-bar";
import plateTitle from "../../../../../components/business/plateTitle";
import {mapGetters} from "vuex";
import {Dialog, Toast} from "vant";
import moment from "moment";

// 纤芯信息-已占用
let map_fiber_occupied = {
  "FIBER_NAME": "所属光缆",           //	String	所属光缆
  "IS_OCCUPY_NAME": "是否占用",    //	String	是否占用
};

// 光路信息
let map_circuit = {
  "LIGHT_NAME": "光路名称",
  "A_EQU_NAME": "A端设备名称",
  "A_PORT": "A端设备端口",
  "Z_EQU_NAME": "Z端设备名称",
  "Z_PORT": "Z端设备端口",
  "MAIN_PREPARE": "主备光路",
};

// 保存时的请求参数
let saveParams = {
  "service_state": "", //	是	string	核查状态（1：一致4：更新）
  "userId": "", //	是	string	用户名id
  "userName": "", //	是	string	用户名名称
  "line_match_id": "", //	是	string	配对纤芯id
  "line_match_name": "", //	是	string	配对纤芯名称
  "line_exam_id": "", //	是	string	纤芯巡视id
  "fiber_exam_id": "", //	是	string	光缆巡视id
  "front_line_id": "", //	否	string	对端纤芯巡视id（若同步信息，必填）
  "click_flag": "0", //	是	string	是否同步（0：否 1：是）
  "tourTim": ""   // 当前时间
};
export default {
  components: {navBar, plateTitle},
  name: "powerInspect",
  data() {
    return {
      idData: {},  // 请求可能用到的ID信息
      fiberTitle: "", // 纤芯信息的标题文字
      fiberData: {}, // 纤芯信息
      circuitData: {}, // 光路信息
      currentPickerList: [], // 当前弹出框的列表
      currentPickerItem: "", // 与当前弹出框相关的项
      saveParams: saveParams, // 核查一致保存时的传参
      buttonText: () => {
        if (this.isCoincide === "一致") return "保存";
        // if(this.operation === "noExist") return "保存";
        if (this.isCoincide === "不一致") return "去完善台账信息";
      },
      isCoincide: "不一致",
      showPicker: false,
      reTourCheck: '1', // 巡视-1 重新编辑-0
      // operation: "modify"
    };
  },
  computed: {
    ...mapGetters(["userData"]),
  },
  onLoad(rawOptions) {
    this.saveParams.line_match_name = "";
    this.saveParams.line_match_id = "";
    
    let options = JSON.parse(rawOptions.obj);
    this.saveParams.userId = this.userData.userId;
    this.saveParams.userName = this.userData.userName;
    
    let requestParams = {
      "batchId": this.userData.batchId, //是	string	批次id
      "lindId": options.CORE_OBJ_ID,          //是	string	纤芯id
      "line_exam_id": options.OBJ_ID,    //是	string	纤芯巡视id
      "is_occupy": options.IS_OCCUPY,  //是	string	是否占用
      "tour_state": options.TOUR_STATE,      //是	string	巡视状态
      "fiber_exam_id": rawOptions.fiber_exam_id,    //是	string	光缆巡视id
      "taskId": ""
    };
    this.idData = requestParams;
    this.getLineMsg(requestParams);
  },
  methods: {
    // 获取核查信息
    getLineMsg(params) {
      this.$api.todoTaskApi.lineMsg(params).then(res => {
        this.idData.taskId = res.data.lineMsg.TASK_ID;
        this.saveParams.line_exam_id = res.data.lineMsg.OBJ_ID;
        this.saveParams.fiber_exam_id = res.data.lineMsg.PAR_OPT;
        this.fiberTitle = `纤芯信息（纤芯${res.data.lineMsg.CORE_NAME}）`
        // todo: 同步对端判断，2023.3.18要求去掉，暂时注释
        // // 如果对端已核查
        // if (res.data.lineMsg.IS_EXIST === 1 && this.reTourCheck === '1') {
        //   // 如果对端未占用/对端无占用信息，直接跳转至纤芯完善页
        //   if (res.data.lineMsg.FRONT_OCCUPY === "5" || res.data.lineMsg.FRONT_OCCUPY === undefined) {
        //     uni.navigateTo({
        //       url: `/pages/workBench/todoTask/cableTour/cableDetail/completeFiber?taskId=${this.idData.taskId}&opticalInfo=${JSON.stringify(res.data.lineMsg)}&source=cableDetail`
        //     });
        //   }
        //   // 如果对端已占用，弹出同步提示
        //   else {
        //     Dialog.confirm({
        //       title: "对端纤芯已核查，是否同步？",
        //       showCancelButton: false,
        //     }).then(() => { // 确认 选择同步-》获取对端信息
        //       this.saveParams.click_flag = "1";
        //       this.saveParams.front_line_id = res.data.lineMsg.FRONT_LINE_ID;
        //       this.getFrontLineMsg(res.data.lineMsg);
        //     }).catch(() => { // 取消
        //       this.saveParams.click_flag = "0";
        //       // 选择不同步-》显示当前纤芯信息
        //       this.fiberData = {
        //         originData: res.data.lineMsg,
        //         baseInfoData: Object.keys(map_fiber_occupied).map(key => {
        //           return {
        //             title: map_fiber_occupied[key],
        //             value: res.data.lineMsg[key]
        //           };
        //         })
        //       };
        //       this.circuitData = {
        //         originData: res.data.line_channel,
        //         baseInfoData: Object.keys(map_circuit).map(key => {
        //           return {
        //             title: map_circuit[key],
        //             value: res.data.line_channel[key]
        //           };
        //         })
        //       };
        //     });
        //   }
        // }
        // // 如果对端未核查，则显示当前纤芯信息
        // else {
        //   this.fiberData = {
        //     originData: res.data.lineMsg,
        //     baseInfoData: Object.keys(map_fiber_occupied).map(key => {
        //       return {
        //         title: map_fiber_occupied[key],
        //         value: res.data.lineMsg[key]
        //       };
        //     })
        //   };
        //   this.circuitData = {
        //     originData: res.data.line_channel,
        //     baseInfoData: Object.keys(map_circuit).map(key => {
        //       return {
        //         title: map_circuit[key],
        //         value: res.data.line_channel[key]
        //       };
        //     })
        //   };
        // }
        this.fiberData = {
          originData: res.data.lineMsg,
          baseInfoData: Object.keys(map_fiber_occupied).map(key => {
            return {
              title: map_fiber_occupied[key],
              value: res.data.lineMsg[key]
            };
          })
        };
        this.circuitData = {
          originData: res.data.line_channel,
          baseInfoData: Object.keys(map_circuit).map(key => {
            return {
              title: map_circuit[key],
              value: res.data.line_channel[key]
            };
          })
        };
      });
    },
    // 获取对端纤芯信息 lineData-本端纤芯信息
    getFrontLineMsg(lineData) {
      // 对端状态为更新,跳转至纤芯完善
      if (lineData.FRONT_SERVICE_STATE == "4") {
        uni.navigateTo({
          url: `/pages/workBench/todoTask/cableTour/cableDetail/completeFiber?taskId=${this.idData.taskId}&opticalInfo=${JSON.stringify(lineData)}&source=cableDetail`
        });
      }
      
      // 对端状态为一致、不存在
      else {
        this.$api.todoTaskApi.frontLineMsg({
          "front_line_id": lineData.FRONT_LINE_ID, // 对端纤芯巡视id
          "is_occupy": lineData.FRONT_OCCUPY // 纤芯占用
        }).then(res => {
          // todo：获取对端配对纤芯信息，后续需要时取消注释
          // this.saveParams.line_match_id = res.data.lineMsg.CORE_PD_ID;
          // this.saveParams.line_match_name = res.data.lineMsg.CORE_PD_ARRANGE;
          this.fiberData = {
            originData: res.data.lineMsg,
            baseInfoData: Object.keys(map_fiber_occupied).map(key => {
              return {
                title: map_fiber_occupied[key],
                value: res.data.lineMsg[key]
              };
            })
          };
          this.circuitData = {
            originData: res.data.line_channel,
            baseInfoData: Object.keys(map_circuit).map(key => {
              return {
                title: map_circuit[key],
                value: res.data.line_channel[key]
              };
            })
          };
        });
      }
    },
    // 弹出式选择框
    checkPickerList(optionItem) {
      this.currentPickerItem = optionItem;
      if (this.currentPickerItem === "isCoincide") {
        this.currentPickerList = [{
          text: "一致",
          value: "一致"
        }, {
          text: "不一致",
          value: "不一致"
        }];
        this.showPicker = true;
      } else if (this.currentPickerItem === "lineMatch") {  // 选择配对纤芯
        this.$api.todoTaskApi.lineMatch({
          "fiber_exam_id": this.idData.fiber_exam_id,
          "line_exam_id": this.idData.line_exam_id
        }).then(res => {
          this.currentPickerList = res.data.map(item => {
            return {
              origin: item,
              text: item.CORE_NAME,
              value: item.OBJ_ID,
            };
          });
          this.showPicker = true;
        });
      }
    },
    // picker确认选择(所有下拉)
    pickerConfirm(selectedOption) {
      if (this.currentPickerItem === "isCoincide") {
        this.isCoincide = selectedOption.value;
      } else if (this.currentPickerItem === "lineMatch") {
        this.saveParams.line_match_id = selectedOption.value;
        this.saveParams.line_match_name = selectedOption.text;
      }
      this.showPicker = false;
    },
    goBack() {
      uni.navigateTo({
        url: `/pages/workBench/todoTask/cableTour/cableDetail/cableDetail?tourId=${this.idData.fiber_exam_id}`
      });
    },
    
    submit() {
      // 一致-保存信息
      if (this.isCoincide === "一致") {
        Dialog.confirm({
          message: "所选巡视结果是否确认？确认后不可变更，如有问题请联系运维人员。",
        }).then(() => {
          this.saveParams.reTourCheck = this.reTourCheck; // 巡视-1 重新编辑-0
          this.saveParams.service_state = "1";
          this.saveParams.tourTim = moment().format("YYYY-MM-DD HH:mm:ss");
          // console.log(this.saveParams, 'this.saveParams');
          this.$api.todoTaskApi.lineExamUpdate(this.saveParams).then(res => {
    
            if (res.code === 0) {
      
              // 如果当前为巡视，且返回data为0，表示重复巡视
              if (this.reTourCheck === "1" && res.data === 0) {
                Dialog.confirm({
                  message: "该纤芯已被巡视，请返回重试",
                }).then(() => {
                  this.goBack();
                });
              } else {
                Dialog.confirm({
                  message: "保存成功，是否继续核查？",
                  confirmButtonText: "继续核查",
                  cancelButtonText: "返回列表"
                })
                  // 继续核查-跳转至下一个纤芯核查页面
                  .then(() => {
                    this.$api.todoTaskApi.continueExamine({
                      fiber_exam_id: this.idData.fiber_exam_id,
                      "lineSn": this.fiberData.originData.CORE_NAME,
                    }).then(res => {
                      if (res.code === 0) {
                        if (res.msg === "完毕") {
                          Dialog.confirm({
                            message: "此光缆的纤芯已核查完毕",
                            showCancelButton: false,
                            confirmButtonText: "返回列表",
                          }).then(() => {
                            this.goBack();
                          });
                        }
                        // 如果下一条未占用或无占用状态，跳转至纤芯完善
                        else if (res.data.IS_OCCUPY === undefined || res.data.IS_OCCUPY === "5") {
                          uni.navigateTo({
                            url: `/pages/workBench/todoTask/cableTour/cableDetail/completeFiber?taskId=${this.idData.taskId}&opticalInfo=${JSON.stringify(res.data)}&source=cableDetail`
                          });
                        }
                        // 如果下一条已占用，跳转至下一条纤芯核查
                        else {
                          uni.navigateTo({
                            url: `/pages/workBench/todoTask/cableTour/cableDetail/fiberInspect?obj=${JSON.stringify(res.data)}&fiber_exam_id=${res.data.PAR_OPT}`
                          });
                        }
                      }
                    });
                  })
                  // 返回列表-跳转至纤芯核查列表
                  .catch(() => {
                    this.goBack();
                  });
              }
      
            } else {
              Toast.fail("操作失败");
            }
    
          });
        }).catch(() => {})
      }

      // 不一致-跳转至纤芯完善
      else if (this.isCoincide === "不一致") {
        console.log(this.fiberData, 'this.fiberData');
        // 跳转完善时，光缆巡视id和纤芯巡视id为本端的对应id
        this.fiberData.originData.PAR_OPT = this.saveParams.fiber_exam_id;
        this.fiberData.originData.OBJ_ID = this.saveParams.line_exam_id;
        uni.navigateTo({
          url: `/pages/workBench/todoTask/cableTour/cableDetail/completeFiber?taskId=${this.idData.taskId}&opticalInfo=${JSON.stringify(this.fiberData.originData)}&source=cableDetail`
        });
      }
    }
  }
};
</script>

<style scoped lang="scss">
.power-inspect-main {
  .header {
    position: sticky;
    top: 0;
    z-index: 9;
  }
  
  .main-container {
    min-height: calc(100vh - #{px2vh(283)});
    padding: px2vh(30) px2vw(30) px2vh(90) px2vw(30);
    background-color: #F8F8F8;
    
    /deep/.van-field__label, 
    /deep/.van-field__control:read-only, 
    /deep/.van-field__body .van-field__control,
    /deep/.van-cell-group .van-cell
    {
      font-size: px2vw(42);
    }
    /deep/.van-field__label {
      width: auto;
    }
    
    .plate-title-1 {
      margin-top: px2vh(30);
      margin-bottom: px2vh(27);
    }
    
    .base-info-container {
      border-radius: $border-radius-base;
      overflow: hidden;
      background-color: #FFFFFF;
    }
    
    .plate-title-2 {
      margin-top: px2vh(60);
      margin-bottom: px2vh(27);
    }
    
    .patrol-info-container {
      font-size: px2vw(42);
      color: #666666;
      border-radius: $border-radius-base;
      overflow: hidden;
      background-color: #FFFFFF;
      
      .van-radio-group {
        padding: px2vh(60) px2vw(42);
      }
      
    }
    
    /deep/ .van-button {
      margin-top: px2vh(100);
      height: px2vh(120);
      color: #fff;
      background-color: #417ADC;
      border: 1px solid #417ADC;
      border-radius: px2vh(60);
    }
    
    .picker-option {
      display: flex;
      justify-content: space-between;
      align-items: baseline;
      width: calc(100vw - 40px);
      
      .circuit {
        width: px2vw(750);
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        span {
          //display: inline-block;
          //white-space: nowrap;
          //animation: 10s wordsLoop linear infinite normal;
        }
      }
    }
  }
  @keyframes wordsLoop {
    0% {
      transform: translateX(10%);
      -webkit-transform: translateX(10%);
    }
    100% {
      transform: translateX(-100%);
      -webkit-transform: translateX(-100%);
    }
  }
}
</style>
